import {ProFormInstance, ProFormSelect, ProFormText, StepsForm} from '@ant-design/pro-components';
import {checkConnection, matchSchemaAndTable} from '@/services/data-media-api'
import {dataSourceCheck, list} from '@/services/data-media-source-api'
import React, {MutableRefObject, useRef, useState} from 'react';
import {Button, message, Modal, Space, Tooltip} from "antd";

export type CreateOrUpdateFormProps = {
  onCancel: (flag?: boolean, formVals?: API.SeniorDataMedia) => void;
  onSubmit: (values: API.SeniorDataMedia) => Promise<boolean>;
  updateModalOpen: boolean;
  values?: Partial<API.SeniorDataMedia>;
  title?: string;
};

const CreateOrUpdateForm: React.FC<CreateOrUpdateFormProps> = (props) => {
  const formRef = useRef<ProFormInstance>();
  const formMapRef = useRef<MutableRefObject<ProFormInstance | undefined>[]>([]);
  const [current,setCurrent] = useState<number>(0);

  const getFieldsValues = () => {
    return formMapRef?.current?.reduce((previousValue, formRef) => {
      // eslint-disable-next-line no-param-reassign
      previousValue = {...previousValue, ...formRef?.current?.getFieldsFormatValue!()};
      return previousValue;
    }, {});
  }

  const handleCheckSchemaAndTable = async () => {
    const {errorFields} = await formRef?.current?.validateFields();
    if (errorFields) {
      return;
    }
    const hide = message.loading('请求中');
    try {
      const curValue = getFieldsValues();
      const res = await matchSchemaAndTable(curValue);
      hide();
      if (res) {
        const node: React.ReactNode[] = res.map((scheme:string, index:number) => (
          <React.Fragment key={index}>
            {scheme}
            <br/>
          </React.Fragment>
        ));
        console.log(node)
        Modal.confirm({title: 'Scheme & Table', content: node});
        return true;
      }
      return false;
    } catch (error) {
      hide();
      return false;
    }
  };
  const handleCheckConnection = async () => {
    const {errorFields} = await formRef?.current?.validateFields();
    if (errorFields) {
      return;
    }
    const hide = message.loading('请求中');
    try {
      const param = getFieldsValues();
      console.log(param);
      const res = await checkConnection(param);
      hide();
      if (res) {
        message.success(res);
        return true;
      }
      return false;
    } catch (error) {
      hide();
      return false;
    }
  };
  return (
    <StepsForm
      formRef={formRef}
      formMapRef={formMapRef}
      onFinish={() => props.onSubmit(getFieldsValues())}
      current={current}
      onCurrentChange={setCurrent}
      formProps={{
        validateMessages: {
          required: '此项为必填项',
        },
      }}
      stepsFormRender={(dom, submitter) => {
        return (
          <Modal
            title="配置数据表"
            width={800}
            onCancel={() => {props.onCancel();setCurrent(0);}}
            open={props.updateModalOpen}
            footer={submitter}
            destroyOnClose={true}
          >
            {dom}
          </Modal>
        );
      }}
    >
      <StepsForm.StepForm
        name="selectDataSource"
        title="选取数据源"
        layout={"horizontal"}
        onFinish={async (params) => {
          const res = await dataSourceCheck({dataSourceId: params?.source?.id});
          if (res) {
            message.info(res);
          }
          return true;
        }}
      >
        <ProFormSelect
          initialValue={props?.values?.source?.id}
          request={() => list({size: 100}).then(res => {
            const {data} = res;
            return data.map((s: API.SeniorDataMediaSource) => ({label: s.name, value: s.id}))
          })}
          label="数据源"
          rules={[{
            required: true,
            message: '请选择数据源'
          }]}
          name={["source", "id"]}
        />
      </StepsForm.StepForm>
      <StepsForm.StepForm
        name="configTable"
        title="配置数据表"
        layout={"horizontal"}
        onFinish={async () => {
          return true;
        }}
      >
        <ProFormText initialValue={props?.values?.id} hidden={true} name='id'/>
        <ProFormText
          initialValue={props.values?.namespace}
          rules={[
            {
              required: true,
              message: 'schema name不能为空',
            },
          ]}
          width="md"
          label="schema name"
          name="namespace"
          tooltip={<>单表配置: alibaba.product<br/>分表配置: alibaba[1-64].product , alibaba.product[01-32]<br/>正则配置:
            (.*).(.*)</>}
        />
        <ProFormText
          initialValue={props.values?.name}
          rules={[
            {
              required: true,
              message: 'table name不能为空',
            },
          ]}
          tooltip={<>单表配置: alibaba.product<br/>分表配置: alibaba[1-64].product , alibaba.product[01-32]<br/>正则配置:
            (.*).(.*)</>}
          width="md"
          label="table name"
          name="name"
        />
        <Space>
          <Tooltip title="表链接验证不支持正则匹配">
            <Button type={'primary'} onClick={() => handleCheckConnection()}>验证连接表</Button>
          </Tooltip>
          <Button type={'primary'} onClick={() => handleCheckSchemaAndTable()}>查询Schema&Table</Button>
        </Space>

      </StepsForm.StepForm>
    </StepsForm>
  );
};

export default CreateOrUpdateForm;
